package TCPEchoServerAndAlient;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

/**
 * Description:
 * User:岁亮亮
 * Date:2025-04-06
 * TIME:14:32
 */
public class TCPEchoSlient {

    Socket socket = null;
    //TCP协议是有连接的 会在socket对象中保存 IP和Port
    public TCPEchoSlient(String serverIP,int serverPort) throws IOException {
        socket = new Socket(InetAddress.getByName(serverIP),serverPort);
    }

    public void start(){
        System.out.println("客户端启动");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            Scanner scannetCOnsole = new Scanner(System.in);
            Scanner scannerSocket = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream)) {
            while(true){
                if(!scannetCOnsole.hasNext()){
                    break;
                }
                //从控制台上读取请求
                String request = scannetCOnsole.next();
                //发送请求 用printWriter发送 与 服务器接收请求格式对应 以空白符结尾 用next()方法读取
                writer.println(request);
                //在writer对象将要发送的请求 写到 socket对象中 而socket对象将要把写入网卡的请求放到内存缓冲区中 攒一波再发送出去
                //IO操作是低效的 为了提高效率降低IO操作的次数 因此缓冲区会等快满时才会将其发送到网卡 真正的发送出去
                // flush()刷新缓冲区 确保数据真正发送出去
                writer.flush();
                //接收响应 与服务器用PRintWriter发送响应
                String response = scannerSocket.next();
                //打印相应
                System.out.println(response);

            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TCPEchoSlient tcpEchoSlient = new TCPEchoSlient("127.0.0.1",9090);
        tcpEchoSlient.start();
    }
}
